package com.easyj.admin.activiti.serviceimpl;

import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.impl.ProcessInstanceQueryProperty;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.easyj.admin.activiti.service.ProcessInstService;
import com.easyj.admin.activiti.vo.ProcessInstQO;
import com.easyj.admin.activiti.vo.ProcessInstVO;
import com.easyj.admin.db.model.Award;
import com.easyj.admin.db.model.Leave;
import com.easyj.admin.db.model.Publish;
import com.easyj.admin.db.model.SocialJob;
import com.easyj.admin.db.model.Training;
import com.easyj.admin.edu.service.AwardService;
import com.easyj.admin.edu.service.LeaveService;
import com.easyj.admin.edu.service.PublishService;
import com.easyj.admin.edu.service.SocialJobService;
import com.easyj.admin.edu.service.TrainingService;
import com.easyj.base.common.page.Page;

@Service
public class ProcessInstServiceImpl implements ProcessInstService{

	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private  HistoryService historyService;
	
	@Autowired
	private  AwardService awardService;
	
	@Autowired
	private  TrainingService trainingService;
	
	@Autowired
	private  SocialJobService socialJobService;
	
	@Autowired
	private  PublishService publishService;
	
	@Autowired
	private  LeaveService leaveService;
	
	
	@Override
	public Page<ProcessInstVO> findProcessInRunning(ProcessInstQO filter) {
		ProcessInstanceQuery query=runtimeService.createProcessInstanceQuery();
		
		if(StringUtils.isNotBlank(filter.getBusinessKey()))
			query.processInstanceBusinessKey(filter.getBusinessKey().trim());
    	if(StringUtils.isNotBlank(filter.getProcDefKey()))
    		query.processDefinitionKey(filter.getProcDefKey().trim());
    	
    	//发起人
    	if(StringUtils.isNotBlank(filter.getStarter())) 
    		query.startedBy(filter.getStarter());
    	
    	
    	if(filter.getState()==1)query.active();
    	else if(filter.getState()==2)query.suspended();
    	
    	query.orderBy(new ProcessInstanceQueryProperty("START_TIME_")).desc();
    	
    	List<ProcessInstVO> list=new ArrayList<ProcessInstVO>();
    	long  instcount =  query.count();

    	if(instcount>0l) {
    		List<ProcessInstance> procList = query.listPage(filter.getPage().getOffset().intValue(), filter.getPage().getLimit()); 
    		for(ProcessInstance p:procList) {
        		ProcessInstVO v=new ProcessInstVO();
        		v.setName(p.getName());
        		v.setProcInstId(p.getId());
        		v.setInitiator(p.getStartUserId());//发起人，登录名...
        		v.setProcDefKey(p.getProcessDefinitionKey());
        		v.setBusinessKey(p.getBusinessKey()); //相关实体ID
        		v.setStartTime(p.getStartTime());   
        		
        		v.setState(p.isSuspended()?"SUSPENDED":"RUNNING");
        		//查询实体，取得实体的状态和其它信息...
        		setProcInfoFromEntity(v);
        		
        		list.add(v);
        	}
    	}
    	 
    	Page<ProcessInstVO> rtn=new Page<ProcessInstVO>(list,instcount,filter.getPage());
      	return rtn;
	}
	
	
	
	@Override
	public long getProcessInRunningCount(ProcessInstQO filter) {
		ProcessInstanceQuery query=runtimeService.createProcessInstanceQuery();
		
		if(StringUtils.isNotBlank(filter.getBusinessKey()))
			query.processInstanceBusinessKey(filter.getBusinessKey().trim());
    	if(StringUtils.isNotBlank(filter.getProcDefKey()))
    		query.processDefinitionKey(filter.getProcDefKey().trim());
    	
    	//发起人
    	if(StringUtils.isNotBlank(filter.getStarter())) 
    		query.startedBy(filter.getStarter());
    	
    	
    	if(filter.getState()==1)query.active();
    	else if(filter.getState()==2)query.suspended();
    	
    	long  instcount =  query.count();

    	return instcount;
	}
	
	
	/**processRuntime 条件简单，只能查询所有人的流程
	   * 查询申请流程(正在运行的)
	 * @param filter
	 
    public Page<ProcessInstVO> findAllProcessInRunning(ProcessInstQO filter) {
    	GetProcessInstancesPayloadBuilder builder=ProcessPayloadBuilder.processInstances();
    	if(StringUtils.isNotBlank(filter.getBusinessKey()))
    		builder.withBusinessKey(filter.getBusinessKey().trim());
    	if(StringUtils.isNotBlank(filter.getProcessDefKey()))
    		builder.withProcessDefinitionKey(filter.getProcessDefKey().trim());
    	
    	if(filter.getState()==1)builder.active();
    	else if(filter.getState()==2)builder.suspended();
    	    	
    	org.activiti.api.runtime.shared.query.Page<org.activiti.api.process.model.ProcessInstance> page=processRuntime.processInstances(Pageable.of(filter.getPage().getOffset().intValue(),filter.getPage().getLimit(),Order.by("startDate",Order.Direction.DESC)), builder.build());
        List<ProcessInstVO> list=new ArrayList<ProcessInstVO>();
    	if(page.getTotalItems()>0 && page.getContent()!=null) {
        	for(org.activiti.api.process.model.ProcessInstance p:page.getContent()) {
        		ProcessInstVO v=new ProcessInstVO();
        		v.setName(p.getName());
        		v.setProcInstId(p.getId());
        		v.setInitiator(p.getInitiator());//发起人，登录名...
        		v.setProcDefKey(p.getProcessDefinitionKey());
        		v.setBusinessKey(p.getBusinessKey()); //相关实体ID
        		v.setStartTime(p.getStartDate());                
        		v.setState(p.getStatus().name());
        		//查询实体，取得实体的状态和其它信息...
        		setProcInfoFromEntity(v);
        		list.add(v);
        	}
        }
    	
    	Page<ProcessInstVO> rtn=new Page<ProcessInstVO>(list,Long.valueOf(page.getTotalItems()),filter.getPage());
    	return rtn;
    }
    */
	
	  /**
	   * 查询历史流程
	 * @param filter
	 */
  public long getHistoryProcessCount(ProcessInstQO filter) {
	 HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery();//.includeProcessVariables();
	 if(StringUtils.isNotBlank(filter.getStarter()))
	    query.startedBy(filter.getStarter().trim());
	 if(StringUtils.isNotBlank(filter.getBusinessKey()))
			query.processInstanceBusinessKey(filter.getBusinessKey().trim());
	 if(StringUtils.isNotBlank(filter.getProcDefKey()))
		 query.processDefinitionKey(filter.getProcDefKey().trim());
	 
	//发起人
	if(StringUtils.isNotBlank(filter.getStarter())) 
		query.startedBy(filter.getStarter());
	
	
	 
	 if(filter.getState()==1)query.finished();
	  else if(filter.getState()==2)query.unfinished();
	  else if(filter.getState()==3)query.deleted();
		               
	long  instcount = (int) query.count();
	return instcount;
}
	
    
    /**
	   * 查询历史流程
	 * @param filter
	 */
  public Page<ProcessInstVO> findHistoryProcess(ProcessInstQO filter) {
	 HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery();//.includeProcessVariables();
	 if(StringUtils.isNotBlank(filter.getStarter()))
	    query.startedBy(filter.getStarter().trim());
	 if(StringUtils.isNotBlank(filter.getBusinessKey()))
			query.processInstanceBusinessKey(filter.getBusinessKey().trim());
	 if(StringUtils.isNotBlank(filter.getProcDefKey()))
		 query.processDefinitionKey(filter.getProcDefKey().trim());
	 
	//发起人
 	if(StringUtils.isNotBlank(filter.getStarter())) 
 		query.startedBy(filter.getStarter());
 	
 	
	 
	 if(filter.getState()==1)query.finished();
 	  else if(filter.getState()==2)query.unfinished();
 	  else if(filter.getState()==3)query.deleted();
 		
	 query.orderByProcessInstanceStartTime().desc();
	                    
	long  instcount = (int) query.count();
	List<HistoricProcessInstance> hisinstList=null;
	if(instcount>0l) {
		hisinstList = query.listPage(filter.getPage().getOffset().intValue(), filter.getPage().getLimit()); 
	}
	    
  	List<ProcessInstVO> list=new ArrayList<ProcessInstVO>();
  	if(instcount>0l && hisinstList!=null) {
      	for(HistoricProcessInstance p:hisinstList) {
      		ProcessInstVO v=new ProcessInstVO();
      		v.setName(p.getName());
      		v.setProcInstId(p.getId());
      		v.setInitiator(p.getStartUserId());//登录名...
      		v.setProcDefKey(p.getProcessDefinitionKey());
      		v.setBusinessKey(p.getBusinessKey()); //相关实体ID
      		v.setStartTime(p.getStartTime());
            v.setEndTime(p.getEndTime()); 
           
      		//v.setState();
      		//查询实体，取得实体的状态和其它信息...
      		setProcInfoFromEntity(v);
      		list.add(v);
      	}
      }
  	
  	Page<ProcessInstVO> rtn=new Page<ProcessInstVO>(list,instcount,filter.getPage());
  	return rtn;
  }
  
    
    private void setProcInfoFromEntity(ProcessInstVO proc) {
    	Long entityId=Long.parseLong(proc.getBusinessKey());
    	if(AwardService.ProcessDefKey.equals(proc.getProcDefKey())) {
    		Award e=awardService.findById(entityId);
    		if(e!=null) {
	    		proc.setApplicantId(e.getApplicantId());
	    		proc.setApplicant(e.getApplicantName());
	    		proc.setStatusName(e.getStatusName());
	    		proc.setStatus(e.getStatus());
	    		proc.setApproveTime(e.getApproveTime());
	    		proc.setApproveId(e.getApproveId());
	    		proc.setApproveName(e.getApproveName());
    		}
    	}
    	else if(TrainingService.ProcessDefKey.equals(proc.getProcDefKey())) {
    		Training e=trainingService.findById(entityId);
    		if(e!=null) {
	    		proc.setApplicantId(e.getApplicantId());
	    		proc.setApplicant(e.getApplicantName());
	    		proc.setStatusName(e.getStatusName());
	    		proc.setStatus(e.getStatus());
	    		proc.setApproveTime(e.getApproveTime());
	    		proc.setApproveId(e.getApproveId());
	    		proc.setApproveName(e.getApproveName());
    		}
    	}else if(SocialJobService.ProcessDefKey.equals(proc.getProcDefKey())) {
    		SocialJob e=socialJobService.findById(entityId);
    		if(e!=null) {
	    		proc.setApplicantId(e.getApplicantId());
	    		proc.setApplicant(e.getApplicantName());
	    		proc.setStatusName(e.getStatusName());
	    		proc.setStatus(e.getStatus());
	    		proc.setApproveTime(e.getApproveTime());
	    		proc.setApproveId(e.getApproveId());
	    		proc.setApproveName(e.getApproveName());
    		}
    	}else if(PublishService.ProcessDefKey.equals(proc.getProcDefKey())) {
    		Publish e=publishService.findById(entityId);
    		if(e!=null) {
	    		proc.setApplicantId(e.getApplicantId());
	    		proc.setApplicant(e.getApplicantName());
	    		proc.setStatusName(e.getStatusName());
	    		proc.setStatus(e.getStatus());
	    		proc.setApproveTime(e.getApproveTime());
	    		proc.setApproveId(e.getApproveId());
	    		proc.setApproveName(e.getApproveName());
    		}	
    	}else if(LeaveService.ProcessDefKey.equals(proc.getProcDefKey())) {
    		Leave e=leaveService.findById(entityId);
    		if(e!=null) {
	    		proc.setApplicantId(e.getApplicantId());
	    		proc.setApplicant(e.getApplicantName());
	    		proc.setStatusName(e.getStatusName());
	    		proc.setStatus(e.getStatus());
	    		proc.setApproveTime(e.getApproveTime());
	    		proc.setApproveId(e.getApproveId());
	    		proc.setApproveName(e.getApproveName());
    		}
    	}
    	
    }

	
}
